package com.banciyuan.bcywebview.biz.main.newdiscover;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.push.Item.BasePush;
import com.banciyuan.bcywebview.base.helper.push.Item.PushError;
import com.banciyuan.bcywebview.base.helper.push.PushFactory;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleSmoothActivity;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleTagSmoothActivity;
import com.banciyuan.bcywebview.biz.main.discover.newestwork.NewestWorkActivity;
import com.banciyuan.bcywebview.biz.main.discover.top.TopFragment;
import com.banciyuan.bcywebview.biz.main.discover.topcreator.TopCreatorActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DiscoverData;
import de.greenrobot.daoexample.model.DiscoverRank;
import de.greenrobot.daoexample.model.HotDiscover;
import de.greenrobot.daoexample.model.HotEvent;
import de.greenrobot.daoexample.model.TagDetail;

/**
 * Created by squall on 2016/5/25.
 */
public class CosDiscoverFragment extends BaseLazyContainerFragment implements View.OnClickListener {

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;

    private PullToRefreshListView mRefresh;
    private ListView mGridView;
    private RequestQueue queue;

    private TextView rela_name;
    private TextView top_user;
    private TextView hot_item;
    private TextView newest_item;
    private ImageView list_label;
    private View relateCircleviewLayout;
    private LinearLayout relateContainer;

    private List<HotDiscover> hlist = new ArrayList<>();
    private List<HotEvent> elist = new ArrayList<>();
    private List<DiscoverRank> rlist = new ArrayList<>();
    private List<HotDiscover> dataTemp = new ArrayList<>();
    private DiscoverListAdapter listAdapter;
    private SparseArray<String> typeMap = new SparseArray<>();


    private int page = 1;
    private boolean end_flag = false;
    private boolean load_flag = false;

    private DiscoverData discoverData = new DiscoverData();

    private int lastSize;
    private int lastPosition;

    private boolean eventEnd;
    private boolean rankEnd;
    private boolean dataEnd;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.not_login_discover, null);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }


    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(getActivity());
        typeMap.put(0, "lastday");
        typeMap.put(6, "week");
        typeMap.put(16, "newPeople");
        typeMap.put(26, "preview");
        typeMap.put(36, "pay");
        for (int i = 0; i < 6; i++) {
            typeMap.put((i * 6) + 3, "event");
        }
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                fetchData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        mRefresh = (PullToRefreshListView) rootview.findViewById(R.id.refreshview);
        mGridView = mRefresh.getRefreshableView();
        View header = View.inflate(getActivity(), R.layout.discover_mould_pic, null);
        initHeaderView(header);
        mGridView.addHeaderView(header);

    }

    private void initHeaderView(View header) {
        rela_name = (TextView) header.findViewById(R.id.circle_rela_name);
        rela_name.setText(getString(R.string.circle_cos));
        list_label = (ImageView) header.findViewById(R.id.list_label);
        list_label.setImageResource(R.drawable.hot_cos);
        top_user = (TextView) header.findViewById(R.id.top_100);
        top_user.setText(getString(R.string.top_coser_100));
        hot_item = (TextView) header.findViewById(R.id.list_name);
        hot_item.setText(getString(R.string.hot_cos));
        newest_item = (TextView) header.findViewById(R.id.more_tv);
        newest_item.setText(getString(R.string.newest_Cos));
        relateCircleviewLayout = header.findViewById(R.id.circle_rela);
        relateContainer = (LinearLayout) relateCircleviewLayout.findViewById(R.id.view_container_hobbycircle);
        top_user.setOnClickListener(this);
        newest_item.setOnClickListener(this);
    }

    @Override
    protected void initAction() {
        mRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                fetchData();
            }
        });

        mRefresh.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!load_flag && !end_flag) {
                    page++;
                    initData();
                }
            }
        });
    }


    private void getRank() {
        String url = HttpUtils.BASE_URL + CoserApi.getCosRankDiscover();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        rlist = gson.fromJson(result, new TypeToken<List<DiscoverRank>>() {
                        }.getType());
                        rankEnd = true;
                        checkEnd();
                    } else {
                        rankEnd = true;
                        checkEnd();
                    }
                } catch (Exception e) {
                    rankEnd = true;
                    checkEnd();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                rankEnd = true;
                checkEnd();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), null);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, null, onSucc, onErrorProxy);
        queue.add(requestParam);
    }

    @Override
    protected void initData() {
        load_flag = true;
        String url = HttpUtils.BASE_URL + CoserApi.getHotCoser();
        final List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        Map<String, String> map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        dataTemp = gson.fromJson(result, new TypeToken<List<HotDiscover>>() {
                        }.getType());
                        dataEnd = true;
                        checkEnd();
                    } else {
                        dataEnd = true;
                        load_flag = false;
                        checkEnd(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dataEnd = true;
                    load_flag = false;
                    checkEnd(false);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                load_flag = false;
                dataEnd = true;
                checkEnd(false);
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(requestParam);
    }

    private void buildMainData(List<HotDiscover> templist, int lastSize) {
        for (; lastPosition <= 36; lastPosition += 1) {
            String type = typeMap.get(lastPosition);
            if (TextUtils.isEmpty(type)) continue;
            if (templist.size() + lastSize >= lastPosition) {
                if (type.equals("event")) {
                    if (elist.size() > 0 && elist.size() >= (lastPosition - 3) / 6) {
                        templist.add(lastPosition - lastSize, parseEventToDiscover(elist.get((lastPosition - 3) / 6)));
                    }
                } else {
                    DiscoverRank dayRank = findRank(typeMap.get(lastPosition));
                    if (dayRank != null) {
                        templist.add(lastPosition - lastSize, parseRankToDiscover(dayRank));
                    }
                }
            } else {
                break;
            }
        }
    }

    private DiscoverRank findRank(String name) {
        for (DiscoverRank d : rlist) {
            if (StringUtil.notNullEqual(d.getType(), name)) {
                return d;
            }
        }
        return null;
    }

    private HotDiscover parseRankToDiscover(DiscoverRank discoverRank) {
        HotDiscover hotDiscover = new HotDiscover();
        hotDiscover.setImg_src(discoverRank.getPost().getCover());
        hotDiscover.setUname(String.format(getString(R.string.cos_rank_farmat), discoverRank.getName()));
        hotDiscover.setUid(discoverRank.getPost().getUid());
        hotDiscover.setRp_id(discoverRank.getPost().getRp_id());
        hotDiscover.setCp_id(discoverRank.getPost().getCp_id());
        hotDiscover.setRank_type(discoverRank.getType());
        hotDiscover.setType("rank");
        return hotDiscover;
    }

    private HotDiscover parseEventToDiscover(HotEvent hotEvent) {
        HotDiscover hotDiscover = new HotDiscover();
        hotDiscover.setImg_src(hotEvent.getPath());
        hotDiscover.setUname(hotEvent.getTitle());
        hotDiscover.setCode(hotEvent.getCode());
        hotDiscover.setType("event");
        return hotDiscover;
    }

    private void renderData(List<HotDiscover> templist) {
        if (page == 1) {
            hlist.clear();
        }
        if (templist.isEmpty()) {
            end_flag = true;
        }
        hlist.addAll(templist);
        if (listAdapter != null) {
            listAdapter.notifyDataSetChanged();
        } else {
            listAdapter = new DiscoverListAdapter(getActivity(), hlist, "cos");
            mGridView.setAdapter(listAdapter);
        }
        mRefresh.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        load_flag = false;
    }

    private void clear() {
        load_flag = false;
        end_flag = false;
        page = 1;
        lastSize = 0;
        lastPosition = 0;
        eventEnd = false;
        rankEnd = false;
        dataEnd = false;
    }

    @Override
    public void fetchData() {
        clear();
        getCoreStatus();
        getRank();
        getHotEvent();
        initData();
    }

    private void checkEnd() {
        checkEnd(true);
    }

    private void checkEnd(boolean succ) {
        if (eventEnd && rankEnd && dataEnd) {
            if (succ) {
                buildMainData(dataTemp, lastSize);
                renderData(dataTemp);
                lastSize = hlist.size();
            } else {
                load_flag = false;
                mRefresh.onRefreshComplete();
                mProgressbarHelper.onFailed();
            }
        }
    }


    private void getHotEvent() {
        String url = HttpUtils.BASE_URL + CoserApi.getHotEvent();
        List<BcyPair> pairs = new ArrayList<>();
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(s);
                        String result = jsonObject.getString("data");
                        elist = gson.fromJson(result, new TypeToken<List<HotEvent>>() {
                        }.getType());
                        popIllegalDiscoverEvent(elist);
                        eventEnd = true;
                        checkEnd();
                    } else {
                        eventEnd = true;
                        checkEnd();
                    }
                } catch (Exception e) {
                    eventEnd = true;
                    checkEnd();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                eventEnd = true;
                checkEnd();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(requestParam);
    }

    private void popIllegalDiscoverEvent(List<HotEvent> tlist) {
        List<HotEvent> illegalData = new ArrayList<>();
        for (int i = 0; i < tlist.size(); i++) {
            BasePush basePush = PushFactory.getPush(tlist.get(i).getCode());
            if (basePush instanceof PushError) {
                illegalData.add(tlist.get(i));
            }
        }
        tlist.removeAll(illegalData);
    }

    private void getCoreStatus() {
        String url = HttpUtils.BASE_URL + TagApi.getStatus();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.NAME, getString(R.string.cos)));
        if (UserDataHelper.ifLogin(getActivity()))
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Map<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                try {
                    if (StatusCodeUtils.dealStatusCode(result, getActivity())) {
                        JSONObject jsonObject = new JSONObject(result);
                        Gson gson = new Gson();
                        discoverData = gson.fromJson(jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA).toString(), new TypeToken<DiscoverData>() {
                        }.getType());
                        TimelineFactory.popNewCircleIllegalType(discoverData.getRela());
                        renderRelaCircle(discoverData.getRela());
                    } else {
                        mProgressbarHelper.onFailed();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(getUserdataRequest);
    }

    private void renderRelaCircle(List<TagDetail> tlist) {
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        relateContainer.removeAllViews();
        for (int i = 0; i < tlist.size(); i++) {
            final TagDetail tagDetail = tlist.get(i);
            View itemView = layoutInflater.inflate(R.layout.categorytag_item, relateContainer, false);
            ImageView ivCategroyTagCover = (ImageView) itemView.findViewById(R.id.iv_categorytag_cover);
            TextView tvCategroyTagName = (TextView) itemView.findViewById(R.id.tv_categorytag_name);
            ImageLoader.getInstance().displayImage(tagDetail.getCover(), ivCategroyTagCover, ImageOptions.options);
            if (!TextUtils.isEmpty(tagDetail.getReal_name())) {
                tvCategroyTagName.setText(tagDetail.getReal_name());
            } else {
                tvCategroyTagName.setText(tagDetail.getTag_name());
            }
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(tagDetail.getWid())) {
                        gotoUtil.gotoAct(getActivity(), CircleSmoothActivity.class, tagDetail.getReal_name(), tagDetail.getWid());
                    } else {
                        Intent intent = new Intent(getActivity(), CircleTagSmoothActivity.class);
                        intent.putExtra("type", "tag");
                        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, tagDetail.getTag_name());
                        startActivity(intent);
                    }
                }
            });
            relateContainer.addView(itemView);
        }
    }


    @Override
    public void selfUpdateData() {
        if (null != mRefresh) {
            mRefresh.setRefreshing();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.top_100:
                gotoUtil.gotoAct(getActivity(), TopCreatorActivity.class, TopFragment.COS_TAG);
                break;
            case R.id.more_tv:
                intent.setClass(getActivity(), NewestWorkActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, TopFragment.COS_TAG);
                startActivity(intent);
                break;

        }
    }
}
